<%- contentFor('mainContent') %>

<div class="row justify-content-center">
<div class="col-md-6">
  <h2 class="mb-4">用户注册</h2>
  <form action="/api/reg" method="post">
    <div class="mb-3">
      <label class="form-label">用户名</label>
      <input type="text" class="form-control" name="username" id="username" required>
    </div>
    <div class="mb-3">
      <label class="form-label">密码</label>
      <input type="password" class="form-control" name="password" id="password" required>
    </div>
    <div class="mb-3">
      <label class="form-label">确认密码</label>
      <input type="password" class="form-control" name="confirmPassword" id="confirmPassword" required>
    </div>
    <div class="mb-3">
      <button type="submit" class="btn btn-primary w-100">立即注册</button>
    </div>
  </form>
  <div class="mb-3">
    <a href="/login" class="btn btn-link w-100">去登录>></a>
  </div>
</div>
</div>


<%- contentFor('pageJS') %>
<script>
  document.querySelector('form').addEventListener('submit', async function (e) {
    e.preventDefault();

    // 禁用提交按钮
    const submitBtn = this.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 提交中...';

    // 清除旧错误提示
    document.querySelectorAll('.alert').forEach(alert => alert.remove());

    // 密码一致性验证
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    if (password !== confirmPassword) {
      showError('密码与确认密码不一致！');
      submitBtn.disabled = false;
      submitBtn.textContent = '用户注册';
      return;
    }

    try {
      const response = await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(new FormData(this))
      });

      const result = await response.json();
      if (result.code === '0000') {
        window.location.href = '/login';
      } else {
        showError(result.msg || '注册失败');
      }
    } catch (error) {
      showError('网络请求异常');
    } finally {
      submitBtn.disabled = false;
      submitBtn.textContent = '用户注册';
    }
  });

  function showError(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'alert alert-danger mt-3';
    errorDiv.textContent = message;
    document.querySelector('.card-body').appendChild(errorDiv);
  }

</script>